<template>
  <!-- 筛选条件 -->
  <view class="panel-container">
    <view class="title">
      <text>筛选</text>
    </view>

    <!--  -->
    <view class="category" v-if="!product_type_one_id">
      <view>分类</view>
      <view
        class="category-item"
        :class="{ active: item.selected }"
        v-for="(item, index) in categoryList"
        :key="index"
        @click="handleCategoryClick(index)"
      >
        <view>{{ item.name }}</view>
      </view>
    </view>

    <view class="filter-list" v-else>
      <!-- 品牌 -->
      <view class="filter-item">
        <view class="filter-item-name">
          <view>品牌</view>
          <view class="all-brand" @click="getAllBrand">全部品牌</view>
        </view>
        <view class="filter-item-name">
          <view style="font-size: 22rpx">已选品牌</view>
        </view>
        <view class="filter-item-list" v-if="brandList.length > 0">
          <view
            class="filter-item-list-item"
            v-for="(item, index) in brandList"
            :class="{ active: item.select }"
            :key="index"
            @click="selectBrand(index)"
            >{{ item.search_name }}</view
          >
        </view>
        <view class="filter-item-list" v-else>
          <view class="no-brand">
            <view>您还未选择品牌！</view>
            <view> 点击【全部品牌】进行选择，至多可同时选择4个品牌</view>
            <image
              class="round-up"
              src="/static/images/round-up.png"
              mode="widthFix"
            />
          </view>
        </view>
      </view>
      <view
        class="filter-item"
        v-for="(item, index) in filterList"
        :key="index"
      >
        <view v-if="item.list.length !== 0">
          <view class="filter-item-name">
            <view>{{ item.search_category.product_type_name }}</view>
          </view>
          <view class="filter-item-list">
            <view
              class="filter-item-list-item"
              v-for="(subItem, subIndex) in item.list"
              :key="subIndex"
              :class="{ active: subItem.select }"
              @click="selectFilter(index, subIndex)"
            >
              <text>{{ subItem.search_name }}</text>
            </view>
          </view>
        </view>
      </view>
      <!-- 价格范围 -->
      <view class="filter-item">
        <view class="filter-item-name">价格</view>
        <view class="filter-item-range">
          <view class="price">
            <text>￥</text>
            <view class="">
              <input
                type="number"
                placeholder="最低价"
                v-model="price_bottom"
                @input="inputValueBottom"
              />
            </view>
          </view>
          <view class="line"></view>
          <view class="price">
            <text>￥</text>
            <!-- <view class=""> {{ currenPrice }} </view> -->
            <view class="">
              <input
                type="number"
                placeholder="最高价"
                v-model="price_top"
                @input="inputValueTop"
              />
            </view>
          </view>
        </view>

        <!-- <view class="pro">
          <sli-vue
            :max="1000"
            @change="changeSli"
            :defaultValue="1000"
          ></sli-vue>
        </view> -->
      </view>
    </view>
    <!-- 底部按钮 -->
    <view class="footer">
      <button class="secondary-button" @click="resetFilter">
        {{ hasFilter ? '清除全部' : '取消' }}
      </button>
      <button class="primary-button" @click="applyFilter">确定</button>
    </view>
  </view>
</template>

<script>
import sliVue from './sli.vue'
export default {
  name: 'FilterPanel',
  components: {
    sliVue,
  },
  props: {
    filterData: {
      type: Array,
      default: () => {
        return []
      },
    },
    product_type_one_id: {
      type: String,
      default: '',
    },
    category_id: {
      type: String,
      default: '',
    },
    top: {
      type: String,
      default: '',
    },
    bottom: {
      type: String,
      default: '',
    },
  },
  mounted() {
    this.initData()
  },
  data() {
    return {
      brandList: [], // 品牌列表
      categoryList: [], // 分类列表
      currentCategory: {}, // 当前分类
      activeId: '', // 1,2,3
      filterList: [], // 筛选条件列表
      currenPrice: 1000,
      price_top: '',
      price_bottom: '',
    }
  },
  watch: {
    product_type_one_id(newVal) {
      this.activeId = newVal
    },
  },
  computed: {
    // 是否有筛选条件
    hasFilter() {
      let hasSelected = this.filterList.some((item) => {
        return item.list.some((subItem) => subItem.select)
      })
      return hasSelected || this.price_top || this.price_bottom
    },
  },
  methods: {
    handleCategoryClick(index) {
      this.categoryList[index].selected = !this.categoryList[index].selected
      this.activeId = this.categoryList
        .filter((item) => item.selected)
        .map((item) => item.id)
        .join(',')
      this.currentCategory = this.categoryList.find((item) => item.selected)
      // this.getFilterList()
    },
    async getAllBrand() {
      this.$emit('getAllBrand')
    },

    selectBrand(index) {
      this.brandList[index].select = !this.brandList[index].select
    },

    selectFilter(index, subIndex) {
      this.filterList[index].list[subIndex].select =
        !this.filterList[index].list[subIndex].select
      console.log(
        'Selected Filter:',
        this.filterList[index],
        this.filterList[index].list[subIndex]
      )
    },
    // 输入框输入事件
    inputValueTop(e) {
      let value = e.detail.value
      console.log(e.detail)
      this.$nextTick(() => {
        this.price_top = value.replace(/[^\d.]/g, '') // 移除非数字字符
      })
    },
    inputValueBottom(e) {
      let value = e.detail.value
      console.log(e.detail)
      this.$nextTick(() => {
        this.price_bottom = value.replace(/[^\d.]/g, '') // 移除非数字字符
      })
    },
    initData() {
      this.$util.showLoading()
      // 获取筛选条件
      this.brandList = uni.getStorageSync('selectedBrand') || []

      this.$emit(
        'currentBrand',
        this.brandList.map((r) => r.search_val)
      )

      // 获取分类
      this.$api.getHotRecommend().then((res) => {
        console.log(res)
        this.categoryList = res.data.hot.map((item) => {
          item.selected = false
          return item
        })
      })
      this.getFilterList()
    },

    // 获取筛选条件
    getFilterList() {
      this.$api
        .getFilterNew({
          product_type_one_id: this.activeId,
          category_id: this.category_id || '',
        })
        .then((res) => {
          console.log(res)
          if (res.code === 0) {
            let list = res.data || []
            this.filterList = list.map((item) => {
              item.list &&
                item.list.map((r) => {
                  r.select = false
                  return r
                })
              return item
            })
            if (this.category_id) {
              this.filterList = this.filterList.filter((item) => {
                return (
                  item.search_category.product_type_keywords !== 'category_name'
                )
              })
            }
            // 如果有传入筛选数据，则设置初始选中状态
            if (this.filterData && this.filterData.length > 0) {
              this.filterData.forEach((filter) => {
                const filterItem = this.filterList.find(
                  (item) =>
                    item.search_category.product_type_keywords === filter.name
                )
                if (filterItem) {
                  filterItem.list.forEach((subItem) => {
                    if (filter.val.includes(subItem.search_val)) {
                      subItem.select = true
                    }
                  })
                }
              })
            }
          }
        })
    },

    resetFilter() {
      if (
        this.activeId !== '' &&
        !this.hasFilter &&
        !this.product_type_one_id
      ) {
        this.activeId = ''
        this.currentCategory = {}
        this.filterList = []
        return
      }
      if (!this.hasFilter) {
        this.$emit('closePanel') // 关闭筛选面板
        return
      }
      // 清除所有筛选条件
      this.price_top = ''
      this.price_bottom = ''
      this.filterList.forEach((item) => {
        item.list.forEach((subItem) => {
          subItem.select = false
        })
      })
    },
    changeSli(val) {
      console.log('Slider Value Changed:', val)
      this.currenPrice = val
    },
    applyFilter() {
      // [{"name":"brand_name","val":["DRAGO","BOTTOLI","ALBIN"]},{"name":"category_name","val":["套西","单西","裤子"]}]

      let brandFilters = []
      const selectedBrand = this.brandList.filter((item) => item.select)
      if (selectedBrand.length > 0) {
        brandFilters.push({
          name: 'brand_name',
          type: 1,
          val: selectedBrand.map((item) => item.search_val),
        })
      }
      const selectedFilters = this.filterList
        .map((item) => {
          return {
            name: item.search_category.product_type_keywords,
            type: item.search_category.type,
            val: item.list
              .filter((subItem) => subItem.select)
              .map((subItem) => subItem.search_val),
          }
        })
        .filter((item) => item.val.length > 0)
      console.log('Selected Filters:', {
        selectedFilters,
        price_top: this.price_top,
        price_bottom: this.price_bottom,
      })
      this.$emit('applyFilter', {
        selectedFilters: [...brandFilters, ...selectedFilters],
        price_top: this.price_top,
        price_bottom: this.price_bottom,
        product_type_one_id: this.activeId || '',
      })
      this.$emit('closePanel') // 关闭筛选面板
    },
  },
}
</script>

<style lang="scss" scoped>
.panel-container {
  width: 100vw;
  height: calc(100vh - 240rpx);
  background-color: #e7e7e7;
  padding: 35rpx;
  box-sizing: border-box;
  overflow: hidden;
  position: relative;
  display: flex;
  flex-direction: column;

  .title {
    font-size: 36rpx;
    font-weight: bold;
    color: #545454;
  }

  .category {
    flex: 1;
    padding-top: 30rpx;
    font-size: 26rpx;
    color: #545454;
    margin-bottom: 26rpx;

    &-item {
      height: 71rpx;
      background: transparent;
      border-radius: 2rpx;
      border: 1rpx solid #c9a063;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 26rpx;
      margin-top: 30rpx;
    }

    .active {
      background: #c9a063;
      color: #fff;
    }
  }

  .filter-list {
    flex: 1;
    overflow-y: auto;
    color: #545454;
    padding-bottom: 180rpx;

    .filter-item {
      margin: 36rpx 0;
      border-bottom: 2rpx solid #dcdcdc;

      .filter-item-name {
        font-size: 26rpx;
        margin-bottom: 26rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .all-brand {
          text-decoration: underline;
        }
      }

      .filter-item-list {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        margin-bottom: 26rpx;

        .filter-item-list-item {
          font-size: 24rpx;
          margin-right: 18rpx;
          height: 72rpx;
          padding: 0 18rpx;
          line-height: 72rpx;
          box-sizing: border-box;
          border-radius: 2rpx;
          margin-bottom: 18rpx;
          border: 2rpx solid var(--main-color);
        }

        .active {
          background-color: var(--main-color);
          color: #fff;
        }

        .no-brand {
          font-size: 20rpx;
          width: 100%;
          color: #979797;
          border: 2rpx solid #979797;
          border-radius: 2rpx;
          line-height: 1.3;
          height: 70rpx;
          box-sizing: border-box;
          display: flex;
          align-items: center;
          flex-direction: column;
          justify-content: center;
          position: relative;

          .round-up {
            width: 28rpx;
            position: absolute;
            right: 26rpx;
          }
        }
      }
    }
  }

  .pro {
    margin-bottom: 26rpx;
  }

  .filter-item-range {
    display: flex;
    align-items: center;
    margin-bottom: 16rpx;

    .price {
      display: flex;
      align-items: center;
      font-size: 24rpx;
      width: 180rpx;
      border-bottom: 2rpx solid #dcdcdc;

      text {
        color: #999;
      }

      view {
        flex: 1;
        margin-left: 10rpx;
        width: 100rpx;
        text-align: center;
        border-radius: 2rpx;
        padding: 10rpx 0;
        box-sizing: border-box;
      }
    }

    .line {
      width: 60rpx;
      height: 2rpx;
      margin: 0 80rpx;
      background-color: #dcdcdc;
    }
  }

  .footer {
    width: 100%;
    background-color: #e7e7e7;
    border-radius: 2rpx;
    padding: 30rpx 33rpx;
    position: fixed;
    z-index: 100;
    bottom: 0;
    left: 0;
    right: 0;
    box-sizing: border-box;
    box-shadow: 0rpx -2rpx 10rpx 0rpx rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: space-between;
  }
}

.all-brand-list {
  width: 100%;
  height: 100%;
  background-color: #fff;
}
</style>
